package io.polly.ldz.reactor.mvc;

import com.alibaba.fastjson.JSON;
import io.polly.ldz.reactor.entity.Question;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

import static io.polly.ldz.reactor.config.KafkaConfig.QUESTION_TOPIC;

/**
 * @Author ldz112@163.com
 * @Classname KafkaProducerController
 * @Version V1.0
 * @Description 生产者
 * @Date 2024/9/29 18:34
 * Copyright (C) 2023 All Rights Reserved
 */
@RestController
@Slf4j
public class KafkaProducerController {

    AtomicLong atomicInteger = new AtomicLong(0L);
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @RequestMapping("/")
    public String helloWorld(){
        String name = "李";
        log.info("hello{}",name);
        return "Hi,"+name;
    }

    @RequestMapping("/kfk/{message}")
    public void sendMsg(@PathVariable("message") String message){

        Question question= new Question(atomicInteger.getAndIncrement(),message);

        kafkaTemplate.send(QUESTION_TOPIC,String.valueOf(question.getQuestionId()), JSON.toJSONString(question)).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable ex) {
                log.error("发送失败"+ex.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> result) {
                log.info("发送成功"+ result.getRecordMetadata().topic() + "-"
                                + result.getRecordMetadata().partition() + "-" + result.getRecordMetadata().offset());
            }
        });
    }
}
